package com.ruoyi.framework.web.service;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.config.properties.CaptchaProperties;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wx.domain.dto.WxUserDTO;
import com.ruoyi.wx.domain.vo.WxUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.naming.ldap.PagedResultsControl;
import javax.xml.parsers.SAXParser;
import java.nio.channels.WritePendingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
	@Autowired
	private TokenService tokenService;

	@Resource
	private AuthenticationManager authenticationManager;

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private CaptchaProperties captchaProperties;

	@Autowired
	private ISysUserService userService;

	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private ISysRoleService sysRoleService;

	@Value("${wx.app-id}")
	private String appId;

	@Value("${wx.app-secret}")
	private String appSecret;

	/**
	 * 登录验证
	 *
	 * @param username 用户名
	 * @param password 密码
	 * @param code     验证码
	 * @param uuid     唯一标识
	 * @return 结果
	 */
	public String login(String username, String password, String code, String uuid) {
		if (captchaProperties.getEnabled()) {
			String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
			String captcha = redisCache.getCacheObject(verifyKey);
			redisCache.deleteObject(verifyKey);
			if (captcha == null) {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
				throw new CaptchaExpireException();
			}
			if (!code.equalsIgnoreCase(captcha)) {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
				throw new CaptchaException();
			}
		}
		// 用户验证
		Authentication authentication = null;
		try {
			// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
			authentication = authenticationManager
				.authenticate(new UsernamePasswordAuthenticationToken(username, password));
		} catch (Exception e) {
			if (e instanceof BadCredentialsException) {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
				throw new UserPasswordNotMatchException();
			} else {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
				throw new CustomException(e.getMessage());
			}
		}
		final LoginUser principal = (LoginUser) authentication.getPrincipal();
		principal.getUser().getRoles().forEach(e -> {
			System.out.println(e.getRoleName());
			if (e.getRoleName().equals(UserConstants.USER_ROLE_STUDENT)) {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "权限不足"));
				throw new CustomException("权限不足！无法访问后台");
			}
		});

		AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		recordLoginInfo(loginUser.getUser());
		// 生成token
		return tokenService.createToken(loginUser);
	}

	/**
	 * 记录登录信息
	 */
	public void recordLoginInfo(SysUser user) {
		user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
		user.setLoginDate(DateUtils.getNowDate());
		user.setUpdateBy(user.getUserName());
		userService.updateUserProfile(user);
	}



	public String getOpenId(String code) {
		String url = "https://api.weixin.qq.com/sns/jscode2session";
		HashMap<String, Object> map = new HashMap<>(4);
		map.put("appid", appId);
		map.put("secret", appSecret);
		map.put("js_code", code);
		map.put("grant_type", "authorization_code");
		String response = HttpUtil.post(url, map);
		JSONObject json = JSONUtil.parseObj(response);
		return json.getStr("openid");
	}

	public WxUserDTO getWxUser() {
		Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
		return null;
	}

	public AjaxResult wxlogin(String code) {
		String openId = getOpenId(code);
		if (openId == null) {
			throw new CustomException("获取授权失败");
		}
		SysUser wxUser = sysUserMapper.selectSysUserByOpenId(openId);
		String token;
		if (wxUser == null) {
			wxUser = new SysUser();
			//生成一个全局唯一的时间戳
			wxUser.setUserName(IdWorker.getId() + "");
			wxUser.setNickName("请修改姓名");
			wxUser.setRemark("小程序登录");
			wxUser.setOpenId(openId);
			//默认密码123456
			wxUser.setPassword(SecurityUtils.encryptPassword("123456"));
			wxUser.setRoleIds(new Long[]{Constants.SYS_DEFAULT_ROLE});
			List<SysRole> list = new ArrayList<>();
			list.add(sysRoleService.selectRoleById(Constants.SYS_DEFAULT_ROLE));
			wxUser.setRoles(list);
			userService.insertUser(wxUser);
		}
		Map<String,Object> map = new HashMap<>();
		map.put("userinfo",wxUser);
		map.put("token",login(wxUser.getUserName(),"123456",openId));
		return AjaxResult.success(map);
	}

	public String login(String username, String password, String openId) {
		String verifyKey = Constants.CAPTCHA_CODE_KEY + openId;
		redisCache.deleteObject(verifyKey);
		// 用户验证
		Authentication authentication = null;
		try {
			// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
			authentication = authenticationManager
				.authenticate(new UsernamePasswordAuthenticationToken(username, password));
		} catch (Exception e) {
			if (e instanceof BadCredentialsException) {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
				throw new UserPasswordNotMatchException();
			} else {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
				throw new CustomException(e.getMessage());
			}
		}
		AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		recordLoginInfo(loginUser.getUser());
		// 生成token
		return tokenService.createToken(loginUser);
	}
}
